#!/usr/bin/python2
#2010.05.15 首次完成,把RsyncFastMirror.sh用python重写
#	    主要功能都已实现, 如测速,注释等
# -*- coding: utf-8 -*-  

import os
import re
import time

def pyrsync(v,*u):
#u[0] source. u[1] dst. u[2] 可选 exluce file
        if u.__len__()==2:
                cmd0="rsync -avh --progress --timeout=10 "+u[0]+" "+u[1]
                print("cmd0=",cmd0)
        cs=os.popen(cmd0).readlines()
        par=re.compile("[0-9.]+kB/s")
        for line in cs:
             if par.search(line):
                  v.append(line)
        return v

	
def pyrate(v):
	sum=0
	for i in v:
		print(i.split()[2].strip("kB/s"))
		sum+=float(i.split()[2].strip("kB/s"))
#	print(sum)  
	if v.__len__() > 0:
		return sum/v.__len__()
	else:
		return 0
#	print("averg=",sum/v.__len__())
	
def file_comment(flist):
	pat=re.compile("#.*$")
	pat2=re.compile("^[ \t]+$")
	for i in range(flist.__len__()):
		if pat.search(flist[i]):
			flist[i]=pat.sub("",flist[i])
		if pat2.search(flist[i]):
			flist.pop(i)
	return flist
	

if __name__ == "__main__":
	MIRROR_FILE="/media/repo/mirror.list"
	TEST_FILE="/extra/os/i686/extra.abs.tar.gz"
	RATE_MINIMUM=100
	RATE_EXPECT=150
	FASTMIRROR=""
	RATE_FAST=0
	
	DST=r"/media/repo/ArchLinux/"
	EXCLUDE_FILE="/media/repo/exclude.txt"

	tmp_file=os.path.join("/tmp",TEST_FILE.split("/")[-1])
	cmd1="rm -f "+tmp_file
	if os.path.exists(tmp_file):
		os.system(cmd1)
	
	print("The Time is :",time.ctime())
	f=file_comment(open(MIRROR_FILE,"r").readlines())
	for line in f:
	   if line !="":
	        u=[]
	        avg=0.0
	        print("line=",line)
	        cmd2=line.strip().rstrip("/")+"/"+TEST_FILE
	        print("cmd2=",cmd2)
	        pyrsync(u,cmd2,"/tmp")
#	        print(u)
#	        print(line)
	        avg=pyrate(u)
	        print("avg=",avg)
	        if RATE_MINIMUM >0 and avg < RATE_MINIMUM :
	                continue
	        if RATE_EXPECT >0 and avg >RATE_EXPECT :
		        FASTMIRROR=line
		        break
	        if RATE_FAST >=0 and avg >RATE_FAST :
		        RATE_FAST=avg
		        FASTMIRROR=line
		        print(avg,FASTMIRROR)
	        os.system(cmd1)

	print(FASTMIRROR)
	if FASTMIRROR !="" :
		cmd0="rsync -avh --progress --timeout=10 --exclude-from="+EXCLUDE_FILE+" "+FASTMIRROR.strip()+"/ "+DST
#		print(type(cmd0),len(cmd0))
		print(cmd0.replace("\n",""))
		os.system(cmd0.replace("\n",""))
